import asyncio
import json
import ssl
import wave
import websockets
# import keyboard
import record
import pyperclip


host = '127.0.0.1'
port = 10095
audio_file = 'audio.wav'

def openAudioFile():
    # open audio file
    with wave.open(audio_file, 'rb') as f:
        frames = f.readframes(f.getnframes())
        audio_bytes = bytes(frames)

        stride = int(60 * 10 / 10 / 1000 * 16000 * 2)
        chunk_num = (len(audio_bytes) - 1) // stride + 1
        print(chunk_num)
        return [chunk_num, stride, audio_bytes]


async def sendToServer():
    [chunk_num, stride, audio_bytes] = openAudioFile()

    uri = 'wss://{}:{}'.format(host, port)
    print(uri)
    ssl_context = ssl.SSLContext()
    ssl_context.check_hostname = False
    ssl_context.verify_mode = ssl.CERT_NONE
    async with websockets.connect(uri, subprotocols=["binary"], ping_interval=None, ssl=ssl_context) as websocket:
        message = json.dumps({
            'mode':'offline',
            'chunk_size':[5, 10, 5],
            'chunk_interval': 10,
            'wav_name':audio_file,
            'is_speaking': True,
            'hotwords': ''
        })
        await websocket.send(message)
        for i in range(chunk_num):
            beg = i * stride
            data = audio_bytes[beg:beg + stride]
            message = data
            #voices.put(message)
            await websocket.send(message)
            if i == chunk_num - 1:
                is_speaking = False
                message = json.dumps({"is_speaking": is_speaking})
                #voices.put(message)
                print(message)
                await websocket.send(message)

        await recvFromServer(websocket)
        # await websocket.close()

 
async def recvFromServer(websocket):
    text_print = ''
    try:
        while True:
            meg = await websocket.recv()
            meg = json.loads(meg)
            wav_name = meg.get("wav_name", "demo")
            text = meg["text"]
            timestamp=""
            if "timestamp" in meg:
                timestamp = meg["timestamp"]

            if meg["mode"] == "offline":
                if timestamp !="":
                    text_print += "{} timestamp: {}".format(text, timestamp)
                else:
                    text_print += "{}".format(text)

                # text_print = text_print[-args.words_max_print:]
                # os.system('clear')
                print("\rpid" + str(id) + ": " + wav_name + ": " + text_print)
                offline_msg_done = True
                break
    except Exception as e:
        print("Exception:", e)


def startRecord():
    # 1. start recording
    # 2. 超过1min未执行ctrl-v，自动stop
    print('start recording...')
    record.record_audio('audio.wav', 60)
    pass

def transferAndPaste():
    # 1. stop recording
    record.stop_record_audio()
    # 2. send to server
    # 3. wait handle result
    asyncio.get_event_loop().run_until_complete(sendToServer())
    # 4. filter sensitive words
    res = ''
    # 5. paste to systemclipboard
    pyperclip.copy(res)
    pass

# if __name__ == '__main__':
# keyboard.add_hotkey('ctrl+0', startRecord, (), suppress=False, timeout=2, trigger_on_release=True)
# keyboard.add_hotkey('ctrl+v', transferAndPaste, ())
# keyboard.wait()
asyncio.run( sendToServer() )
